from lib import common
from db.db_handler import MySQLHandler

login_dict_stu = {'username': '', 'role': ''}


def login(username, password):
    user_info = common.user_exists(username)
    if not user_info:
        return '【用户不存在】'
    else:
        if user_info['role'] != 'student':
            return f'【当前用户 {username} 权限错误！】'
        true_pwd = user_info['password']
        salt = user_info['password'][-4:]
        input_pwd = common.encrypt_data(password, salt)
        if true_pwd != input_pwd:
            return '【用户名或密码有误】'
        else:
            login_dict_stu['username'] = username
            login_dict_stu['role'] = 'student'
            return '【登录成功】'


def register(username, password):
    user_info = common.user_exists(username)
    if user_info:
        return '【用户已存在,请不要重复注册！】'
    else:
        mysql_obj = MySQLHandler()
        salt = common.generate_code(4)
        password = common.encrypt_data(password, salt)
        res = mysql_obj.insert_data('account', username=username, password=password, role='student')
        if res == 0:
            return '【注册失败，请联系系统管理员】'
        elif res == 1:
            return f'【用户 {username} 注册成功】'
        else:
            return '【发生了意料之外的错误，请联系系统管理员检查】'


def select_course(course_id):
    mysql_obj = MySQLHandler()
    student_id = common.stu_username2stu_id(username=login_dict_stu['username'])['id']
    course_name = common.course_id2course_name(course_id=course_id)['course_name']
    res = mysql_obj.insert_data('course2student', course_id=course_id, student_id=student_id)
    if res == 0:
        return '【选课失败,请联系系统管理员】'
    elif res == 1:
        return f'【课程 {course_name} 选课成功】'
    else:
        return f'【选课失败 {res} 】'


def check_score():
    stu_id = common.stu_username2stu_id(login_dict_stu['username'])['id']
    mysql_obj = MySQLHandler()
    search_sql = "select * from course2student where student_id=%(stu_id)s"
    res = mysql_obj.search_one(sql=search_sql, stu_id=stu_id)
    course_name = common.course_id2course_name(course_id=res['course_id'])['course_name']
    txt = f"当前用户【{login_dict_stu['username']}】: 课程【{course_name}】的成绩为【{res['scores']}】"
    return txt
